﻿using Entity;
using Entity.DbEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace SysFrameWork
{
   public class PubMethod
    {
        /// <summary>
        /// 获取当前时间(yyyy-MM-dd HH:mm:ss)
        /// </summary>
        /// <returns></returns>
       public string getNow(int days = 0)
        {
            if (days == 0)
            {
                return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                return DateTime.Now.AddDays(days).ToString("yyyy-MM-dd HH:mm:ss");
            }
        }
        /// <summary>
        /// 获取当前时间(yyyy-MM-dd)
        /// </summary>
        /// <returns></returns>
        public string getNowDate(int days = 0)
        {
            if (days == 0)
            {
                return DateTime.Now.ToString("yyyy-MM-dd");
            }
            else
            {
                return DateTime.Now.AddDays(days).ToString("yyyy-MM-dd");
            }
        }
        /// <summary>
        /// 获取时间字符串(yyyyMMddHHmmss)
        /// </summary>
        /// <returns></returns>
        public string getTimeString(int days = 0)
        {
            if (days == 0)
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssfff");
            }
            else
            {
                return DateTime.Now.AddDays(days).ToString("yyyyMMddHHmmssfff");
            }
           
        }
        /// <summary>
        /// 创建检索条件
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public StringBuilder CreateSelectCondition(StringBuilder sb, string condition)
        {
            if (!string.IsNullOrWhiteSpace(condition))
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                foreach (JProperty obj in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {
                        if (!string.IsNullOrWhiteSpace(sb.ToString()))
                        {
                            sb.Append(" and ");
                        }
                        sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                    }
                }
            }
            return sb;
        }

        /// <summary>
        /// 创建编码
        /// </summary>
        /// <param name="codeType">数据类型</param>
        /// <param name="memo">备注</param>
        /// <param name="barLength">流水码长度</param>
        /// <returns></returns>
        public string CreateCodeInfo(string codeType, string memo, int barLength,int codeCount=1)
        {
            Tools.TxtLogHelper txt = new Tools.TxtLogHelper();
            CommandService.Commands cmd = new CommandService.Commands();
            try
            {
                if (barLength < 1)
                {
                    barLength = int.Parse(Tools.ConfigReader.Reader["CodeLength"]);
                }
                string date = DateTime.Now.ToString("yy-MM-dd");
           
                string sql = "select * from sys_SystemCodes_Bank where date='" + date + "' and tCode='" + codeType + "'";
                var table = cmd.GetDataTable(sql);
                DbCodeBank code = new DbCodeBank();
                code.date = date;
                code.tCode = codeType;
                int startNum = 0;
                OperateModel op = new OperateModel();
                if (table.Rows.Count < 1)
                {
                    #region 不存在记录
                    //startNum = 1;
                    startNum = 0;
                    code.memo = memo;
                    code.num = codeCount;
                    op.Types = OperateModel.OperateType.Add;

                    #endregion
                }
                else
                {
                    #region 存在记录
                    startNum = int.Parse(table.Rows[0]["num"].ToString());
                    code = new DbCodeBank();
                    code.Id = int.Parse(table.Rows[0]["id"].ToString());
                    code.num = int.Parse(table.Rows[0]["num"].ToString()) + codeCount;
                    op.Types = OperateModel.OperateType.Edit;
                    op.Conditions = "Id";
                    #endregion
                }
                op.Data = code;
                List<OperateModel> list = new List<OperateModel>();
                list.Add(op);
                var r = cmd.MoreUpdate(list);
                if (r.Result)
                {
                    string codes = "";
                    #region 生成唯一标识码
                    for (int i = 1; i <= codeCount; i++)
                    {
                        startNum++;
                        string newNum = "";
                        //newNum.PadLeft(barLength, '0');
                        newNum= startNum.ToString().PadLeft(barLength, '0');
                        //codeType为BP时是条码，客户只要流水号的条码，所以这不用加英文前缀
                        if (codeType == "BP")
                        {
                            codes += string.Format("{0}{1},", date.Replace("-", ""), newNum);
                        }
                        else
                        {
                            codes += string.Format("{0}{1}{2},", codeType.ToUpper(), date.Replace("-", ""), newNum);
                        }
                    }
                    #endregion
                    return codes.TrimEnd(',');

                }
            }
            catch (Exception ex)
            {
                txt.AddLogMsg("createCode方法异常：" + ex.Message);
            }
            return null;
        }

        /// <summary>
        /// 创建设备编码
        /// </summary>
        /// <param name="codeType">数据类型</param>
        /// <param name="sbCode">设备编码</param>
        /// <returns></returns>
        public string CreateSBCodeInfo(string codeType, string sbCode, int codeCount = 1)
        {
            Tools.TxtLogHelper txt = new Tools.TxtLogHelper();
            CommandService.Commands cmd = new CommandService.Commands();
            try
            {
                string codes = "";
                string date = DateTime.Now.ToString("yy-MM-dd");
                #region 生成唯一标识码
                for (int i = 1; i <= codeCount; i++)
                {
                    codes += string.Format("{0}{1}{2},", codeType.ToUpper(), date.Replace("-", ""), sbCode);
                }
                #endregion
                return codes.TrimEnd(',');
            }
            catch (Exception ex)
            {
                txt.AddLogMsg("CreateSBCodeInfo：" + ex.Message);
            }
            return null;
        }

        /// <summary>
        /// 创建计划编码
        /// </summary>
        /// <param name="codeType"></param>
        /// <param name="memo"></param>
        /// <param name="barLength"></param>
        /// <returns></returns>

        public string CreatePlanCodeInfo(string codeType, string memo, int barLength)
        {
            Tools.TxtLogHelper txt = new Tools.TxtLogHelper();
            CommandService.Commands cmd = new CommandService.Commands();
            try
            {
                if (barLength < 1)
                {
                    barLength = int.Parse(Tools.ConfigReader.Reader["CodeLength"]);
                }
                string date = DateTime.Now.ToString("yyyy-MM-dd");
              //  string date = DateTime.Now.ToString("yyMMdd-");
                DbCodeBank code = new DbCodeBank();
                code.date = date;
                code.tCode = codeType;
                var queList = cmd.GetDataByObject<DbCodeBank>(code);
                string newNum = "";
                OperateModel op = new OperateModel();
                if (queList.Count < 1)
                {
                    #region 不存在记录
                    newNum = "1";
                    for (int i = 0; i < barLength - 1; i++)
                    {
                        newNum = "0" + newNum;
                    }
                    code.memo = memo;
                    code.num = 1;
                    op.Types = OperateModel.OperateType.Add;

                    #endregion
                }
                else
                {
                    #region 存在记录
                    newNum = Convert.ToString(queList[0].num + 1);
                    for (int i = 0; i < barLength - (queList[0].num + 1).ToString().Length; i++)
                    {
                        newNum = "0" + newNum;
                    }
                    code = queList[0];
                    code.num = code.num + 1;
                    op.Types = OperateModel.OperateType.Edit;
                    op.Conditions = "Id";
                    #endregion
                }
                op.Data = code;
                List<OperateModel> list = new List<OperateModel>();
                list.Add(op);
                var r = cmd.MoreUpdate(list);
                if (r.Result)
                {
                    return codeType.ToUpper() + DateTime.Now.ToString("yyMMdd-") + newNum;
                }
            }
            catch (Exception ex)
            {
                txt.AddLogMsg("createCode方法异常：" + ex.Message);
            }
            return null;
        }
        /// <summary>
        /// Excel导出单元格样式(标题)
        /// </summary>
        /// <param name="book"></param>
        /// <param name="isCenter">是否居中</param>
        /// <param name="isBold">是否加粗</param>
        /// <returns></returns>
        public ICellStyle ExcelTitleStyle(HSSFWorkbook book, bool isCenter = false, bool isBold = true, short fontSize = 10)
        {
            var style = book.CreateCellStyle();
            style.VerticalAlignment = VerticalAlignment.Center;
            if (isCenter)
            {
                style.Alignment = HorizontalAlignment.Center;
            }
            else
            {
                style.Alignment = HorizontalAlignment.Left;
            }
            if (isBold)
            {
                IFont f = book.CreateFont();
                f.Boldweight = (short)FontBoldWeight.Bold;
                f.FontHeightInPoints = fontSize;

                style.SetFont(f);
            }
            return style;
        }
        /// <summary>
        /// Excel导出单元格样式(数据表)
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        public ICellStyle ExcelBodyStyle(HSSFWorkbook book,bool isBorder=true, bool isCenter = false)
        {
            var style = book.CreateCellStyle();
            if (isBorder)
            {
                style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            }
            style.VerticalAlignment = VerticalAlignment.Center;
            if (isCenter)
            {
                style.Alignment = HorizontalAlignment.Center;
            }
            IDataFormat dataformat = book.CreateDataFormat();
            style.DataFormat = dataformat.GetFormat("text");
            return style;
        }
        /// <summary>
        /// 复制实体内容
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public T EntityCopy<T>(object entity)
        {
            return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(entity));
        }
        //读取excel内容
        public System.Data.DataSet GetExcelData(string excelFilePath)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Sheets sheets;
            Microsoft.Office.Interop.Excel.Workbook workbook = null;
            object oMissiong = System.Reflection.Missing.Value;

            DataSet dataSet = new DataSet();
            string cellContent;
            try
            {
                if (app == null)
                {
                    return null;
                }
                workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong,
                    oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);

                sheets = workbook.Worksheets;
                for (int p = 1; p <= sheets.Count; p++)
                {
                    DataTable dt = new DataTable();
                    Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(p);//读取第一张表

                    for (int j = 1; j <= workSheet.UsedRange.Columns.Count; j++)
                    {

                        Microsoft.Office.Interop.Excel.Range _range = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[1, j];
                        if (_range.Text.ToString().Trim() == "")
                            dt.Columns.Add("EQUIPMENT");
                        else
                            dt.Columns.Add(_range.Text.ToString().Trim());

                    }
                    for (int i = 2; i <= workSheet.UsedRange.Rows.Count; i++)
                    {
                        DataRow dr = dt.NewRow();
                        for (int j = 1; j <= workSheet.UsedRange.Columns.Count; j++)
                        {
                            Microsoft.Office.Interop.Excel.Range _range = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[i, j];
                            cellContent = (_range.Value2 == null) ? "" : _range.Text.ToString().Trim();
                            dr[j - 1] = cellContent;
                        }
                        dt.Rows.Add(dr);
                    }
                    dataSet.Tables.Add(dt);
                }
            }
            finally
            {
                workbook.Close(false, oMissiong, oMissiong);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                workbook = null;
                app.Workbooks.Close();
                app.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                app = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return dataSet;
        }
        /// <summary>
        /// 验证内容否是数值类型
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool IsNum(string str)
        {
            Regex r = new Regex(@"^[+-]?\d*(,\d{3})*(\.\d+)?$");
            if (r.IsMatch(str))
            {
                return true;
            }
            return false;
        }
    }
}
